<?php

require_once(__DIR__ . '/../vendor/autoload.php');

use Beanbun\Beanbun;
use Beanbun\Lib\Db;

Db::$config = [
    'kmmovie' => [
        'server' => '10.1.1.247',
        'port' => '3306',
        'username' => 'root',
        'password' => 'root',
        'database_name' => 'kmmovie',
        'database_type' => 'mysql',
        'charset' => 'utf8',
    ],
];


$beanbun = new Beanbun;
$beanbun->name = 'douban';
$beanbun->count = 10;
$beanbun->interval = 50;     // 间隔时间
$beanbun->seed = [
    'https://movie.douban.com/',
];
$beanbun->logFile = __DIR__ . '/douban_access' . date('Y-m-d-H-i-s') . '.log';
$beanbun->urlFilter = [
    '/^https:\/\/movie.douban.com\/subject\/(\d*)\/$/',
    '/^https:\/\/movie.douban.com\/tag\//',
];
// 设置队列
$beanbun->setQueue('memory', [
    'host' => '127.0.0.1',
    'port' => '2207'
]);
//$beanbun->userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3026.3 Safari/537.36';
$beanbun->startWorker = function ($beanbun) {
    $beanbun->log("startWorker worker id {$beanbun->id} start success.");
};

$beanbun->beforeDownloadPage = function($beanbun) {
//    $beanbun->log("user-agent is {$beanbun->options['headers']['user-agent']}.");
    $beanbun->log("beforeDownloadPage worker id {$beanbun->id} $beanbun->url");
    $beanbun->options['proxy'] = '10.1.1.247:8888';
    $beanbun->options['verify'] = false;
    $beanbun->options['cookies'] = \GuzzleHttp\Cookie\CookieJar::fromArray([
        'bid' => 'WcYXCfNasag',
        'dbcl2' => '"160310448:tdxMO+HIDLU"',
    ], '.douban.com');
};

$beanbun->afterDownloadPage = function ($beanbun) {
    $beanbun->log("afterDownloadPage worker id {$beanbun->id} $beanbun->url");

//    $beanbun->log(json_encode(addslashes(str_replace(array("\n", '    '), '',  $beanbun->page))));
    if (preg_match('/^https:\/\/movie.douban.com\/subject\/(\d*)\/$/', $beanbun->url) !== false && $beanbun->page) {
        $doubanPhpRow = Db::instance('kmmovie')->select("km_tl_douban_php2", [
            "id",
            "url"
        ], [
            "url" => $beanbun->url
        ]);

        if (empty($doubanPhpRow)) {
            Db::instance('kmmovie')->insert("km_tl_douban_php2", [
                "url" => $beanbun->url,
                "content" => addslashes(str_replace(array("\n", '    '), '', $beanbun->page))
            ]);
        }
    }


};

$beanbun->stopWorker = function ($beanbun) {
    $beanbun->log("beanbun worker id {$beanbun->id} stop success.");
};

$beanbun->start();